package cn.fl.customer.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cmm.mid.core.framework.dto.BaseParamDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstNpSocialRlService;
import cn.fl.customer.transform.CstNpSocialRlVOTransform;
import cn.fl.customer.vo.CstNpSocialRlVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import fl.customer.facade.customer.api.ICustomerApiService;
import fl.customer.facade.customer.condition.CstNpSocialRlQueryCondition;
import fl.customer.facade.customer.dto.CstNpSocialRlDTO;
import tc.esign.facade.esign.api.ICfcaUsrApiService;
import tc.esign.facade.esign.dto.req.user.ApiMobileRealNameValidateDTO;

@Service
public class CstNpSocialRlServiceImpl implements ICstNpSocialRlService {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(CstNpSocialRlServiceImpl.class);

    /**
     * 客户 API服务
     */
    @Autowired
    private ICustomerApiService customerApiService;

    /**
     * 本地数据字典
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private ICfcaUsrApiService cfcaUsrApiService;

    private static final String CODE_IS_ACTUAL_PAYER_CD = "CST0062";

    @Override
    public CstNpSocialRlVO selectById(Long id) {
        if (StringUtils.isEmpty(id)) return null;
        CstNpSocialRlDTO dto = this.customerApiService.selectCstNpSocialRlById(id);
        this.setCstNpSocialRlDTODicInfo(dto);
        return CstNpSocialRlVOTransform.toVO(dto);
    }

    /**
     * 设置数据字典项目
     *
     * @param dto
     */
    private void setCstNpSocialRlDTODicInfo(CstNpSocialRlDTO dto) {
        if (null == dto) return;

        Map<String, Map<String, String>> map = null;
        try {
            String sysCd = CurrentThreadContext.getCurrentSysCd();
            String orgCd = CurrentThreadContext.getCurrentOrgCd();
            List<String> codeGrpCdList = new ArrayList<>();
            codeGrpCdList.add(DictionaryConstant.CODE_GRP_CERT_TYP_CD);
            codeGrpCdList.add(DictionaryConstant.CODE_GRP_RL_TYP_CD);
            codeGrpCdList.add(DictionaryConstant.CODE_GRP_GENDER_CD);
            codeGrpCdList.add(DictionaryConstant.CODE_GRP_CST_NATION_CD);
            codeGrpCdList.add(CODE_IS_ACTUAL_PAYER_CD);
            map = this.sysDictionaryApiService.searchMultiGroupToMap(sysCd, orgCd, codeGrpCdList);
        } catch (BaseException e) {
            BaseLogUtils.info(logger, "setCstNpSocialRlDTODicInfo", "获取数据字典项失败!" + e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.error(logger, "setCstNpSocialRlDTODicInfo", "获取数据字典项失败!" + e.getMessage());
        } finally {
            if (CollectionUtils.isMapEmpty(map)) {
                map = new HashMap<>();
            }
        }

        Map<String, String> certTypCdMap = map.get(DictionaryConstant.CODE_GRP_CERT_TYP_CD);
        if (CollectionUtils.isMapNotEmpty(certTypCdMap)) {
            dto.setCertTypCdNm(certTypCdMap.get(dto.getCertTypCd()));
        }
        Map<String, String> nationCdMap = map.get(DictionaryConstant.CODE_GRP_CST_NATION_CD);
        if (CollectionUtils.isMapNotEmpty(nationCdMap)) {
            dto.setNationNm(nationCdMap.get(dto.getNation()));
        }

        Map<String, String> rlTypCdMap = map.get(DictionaryConstant.CODE_GRP_RL_TYP_CD);
        if (CollectionUtils.isMapNotEmpty(rlTypCdMap)) {
            dto.setRlTypCdNm(rlTypCdMap.get(dto.getRlTypCd()));
        }

        Map<String, String> genderCdMap = map.get(DictionaryConstant.CODE_GRP_GENDER_CD);
        if (CollectionUtils.isMapNotEmpty(genderCdMap)) {
            dto.setGenderCdNm(genderCdMap.get(dto.getGenderCd()));
        }

        Map<String, String> isActualPayerMap = map.get(CODE_IS_ACTUAL_PAYER_CD);
        if (CollectionUtils.isMapNotEmpty(isActualPayerMap)) {
            Integer isActualPayer = dto.getIsActualPayer();
            if(isActualPayer!=null){
                dto.setIsActualPayerNm(isActualPayerMap.get(isActualPayer.toString()));
            }
        }
    }

    @Override
    public Long add(CstNpSocialRlVO entity) {
        if (null == entity) return null;
        return this.customerApiService.addCstNpSocialRl(CstNpSocialRlVOTransform.toDTO(entity));
    }

    @Override
    public boolean removeByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) return false;
        return this.customerApiService.removeCstNpSocialRlByIds(ids);
    }

    @Override
    public boolean modify(CstNpSocialRlVO entity) {
        if (null == entity) return false;
        return this.customerApiService.modifyCstNpSocialRl(CstNpSocialRlVOTransform.toDTO(entity));
    }

    @SuppressWarnings("unchecked")
    @Override
    public Pager searchListPage(Pager page) {
        if (null == page) page = new Pager();
        page = this.customerApiService.searchCstNpSocialRlPage(page);
        List<CstNpSocialRlDTO> dtoList = (List<CstNpSocialRlDTO>) page.getResultList();
        page.setResultList(CstNpSocialRlVOTransform.toVOList(dtoList));
        return page;
    }


    @Override
    public List<CstNpSocialRlDTO> searchList(CstNpSocialRlQueryCondition condition) {
        return this.customerApiService.searchCstNpSocialRlList(condition);
    }

    @Override
    public List<KeyValueVO> searchRlTypCdList() {
        return this.sysDictionaryApiService.getKvList(DictionaryConstant.CODE_GRP_RL_TYP_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

    /**
     * @MethodName checkThreeElements
     * @Description: 校验三要素信息
     * @Author: wangpengtao@lionbridgecapital.cn
     * @CreateDate: 2019/6/19 19:11
     * @Version: V1.0.0
     * @Param cstNm
     * @Param certNo
     * @Param mp
     * @Return java.lang.Boolean
     * @UpdateRemark [序号][YYYY-MM-DD] [更改人姓名][变更描述]
     */
    @Override
    public Boolean checkCustThreeElements(String cstNm, String certNo, String mp) throws BaseException {
        Boolean rtn = false;
        BaseParamDTO baseParam = new BaseParamDTO();
        ApiMobileRealNameValidateDTO mobileRealNameValidate = new ApiMobileRealNameValidateDTO();
        try {
            baseParam.setSysCd(CurrentThreadContext.getCurrentSysCd()); //系统代码
            baseParam.setChannelCd("CHL0001"); //渠道代码：融资租赁后台管理
            baseParam.setServiceCd(CurrentThreadContext.getCurrentSysCd()); //服务代码--暂用
            baseParam.setFrontCd(CurrentThreadContext.getCurrentSysCd()); //前端代码--暂用

            mobileRealNameValidate.setUserName(cstNm);
            mobileRealNameValidate.setIdentificationNo(certNo);
            mobileRealNameValidate.setMobilePhone(mp);
            mobileRealNameValidate.setBussinessTypeCd("CUST"); //业务代码:客户 CUST

            //有一个为空就不调用接口校验
            if (StringUtils.isEmpty(cstNm) || StringUtils.isEmpty(certNo) || StringUtils.isEmpty(mp)) {
                BaseLogUtils.info(logger, "checkThreeElements", "手机号三要素：参数不能为空!  =>验证参数:" + com.alibaba.fastjson.JSONObject.toJSONString(mobileRealNameValidate), CurrentThreadContext.getCurrentUserName());
                return rtn;
            }

            DataResultDTO result = this.cfcaUsrApiService.mobileRealNameValidate(mobileRealNameValidate, baseParam);
            if (BaseConstant.IS_YESNO_YES == result.getSuccess()) {
                rtn = true;
                BaseLogUtils.info(logger, "checkThreeElements", "手机号三要素：验证通过!  =>验证参数:" + com.alibaba.fastjson.JSONObject.toJSONString(mobileRealNameValidate), CurrentThreadContext.getCurrentUserName());
            } else {
                BaseLogUtils.info(logger, "checkThreeElements", "手机号三要素：验证不通过!  =>验证参数:" + com.alibaba.fastjson.JSONObject.toJSONString(mobileRealNameValidate), CurrentThreadContext.getCurrentUserName());
            }
        } catch (BaseException ex) {
            BaseLogUtils.error(logger, "checkThreeElements", "验证手机号三要素操作失败! =>验证参数:" + com.alibaba.fastjson.JSONObject.toJSONString(mobileRealNameValidate), CurrentThreadContext.getCurrentUserName(), ex);
            throw new BaseException("调用检测失败");
        } catch (Exception ex) {
            BaseLogUtils.error(logger, "checkThreeElements", "验证手机号三要素操作失败! =>验证参数:" + com.alibaba.fastjson.JSONObject.toJSONString(mobileRealNameValidate), CurrentThreadContext.getCurrentUserName(), ex);
            throw new BaseException("调用检测失败");
        }
        return rtn;
    }
}
